<template>
  <v-page
    v-model="refreshing"
    background="#f5f6fa"
    footer-background="white"
    padding-top="24rpx"
    :loading="loading"
    :footer="ableToCancel || ableToModify"
    @refresh="refreshHandle"
  >
    <template #header>
      <v-navbar title="售后详情" native />
    </template>
    <template #default>
      <template v-if="aftersales">
        <view v-if="progressCurrent" class="aftersales-block">
          <view class="block-info-title">
            {{ progressCurrent.main }}
          </view>
          <view v-if="progressCurrent.sub" class="block-info-sub">
            {{ progressCurrent.sub }}
          </view>
          <view v-if="progressCurrent.content" class="block-info-content">
            <template
              v-for="(item, index) in progressCurrent.content"
              :key="index"
            >
              <wd-count-down
                v-if="item.time"
                :time="item.time"
                format="DD天 HH:mm:ss"
              />
              <text v-else :class="{ highlight: item.highlight }">
                {{ item.text }}
              </text>
            </template>
          </view>
          <v-steps
            :current="stepsCurrent"
            :status="
              stepsList && stepsCurrent === stepsList.length - 1
                ? 'success'
                : 'normal'
            "
            :list="stepsList"
          />
        </view>
        <template
          v-if="
            (aftersalesProgress?.mini_status === 'MERCHANT_BUYER_UNSHIPPED' ||
              aftersalesProgress?.mini_status === 'BUYER_SHIPPED_C') &&
              aftersales.merchant_recipient_info
          "
        >
          <view class="aftersales-block">
            <view class="block-info-header">
              <view class="block-info-title">
                退货地址
              </view>
              <view class="copy-button" @click="copyHandle">
                复制
              </view>
            </view>
            <view class="block-info-item">
              <view class="label">
                收货人
              </view>
              <view class="content">
                {{ aftersales.merchant_recipient_info.recipient }}
              </view>
            </view>
            <view class="block-info-item">
              <view class="label">
                联系电话
              </view>
              <view class="content">
                {{ aftersales.merchant_recipient_info.recipient_mobile }}
              </view>
            </view>
            <view class="block-info-item">
              <view class="label">
                收货地址
              </view>
              <view class="content">
                {{ address }}
              </view>
            </view>
          </view>
          <view class="aftersales-block" @click="navigateToExpress">
            <view class="block-info-header">
              <view class="block-info-title">
                买家寄回
              </view>
              <view class="express">
                <view v-if="buyerShippingText" class="text">
                  {{ buyerShippingText }}
                </view>
                <view v-else class="placeholder">
                  请您寄回商品，并填写物流信息
                </view>
                <view class="icon">
                  <wd-icon name="arrow-right" size="24rpx" color="#999999" />
                </view>
              </view>
            </view>
          </view>
        </template>
      </template>
      <view class="aftersales-block">
        <view class="block-info-title">
          售后信息
        </view>
        <view class="block-info-item">
          <view class="label">
            售后ID
          </view>
          <view class="content">
            {{ aftersales?.id }}
          </view>
        </view>
        <view class="block-info-item">
          <view class="label">
            申请时间
          </view>
          <view class="content">
            {{ aftersales?.apply_time }}
          </view>
        </view>
        <view class="block-info-item">
          <view class="label">
            售后类型
          </view>
          <view class="content">
            {{ aftersalesType }}
          </view>
        </view>
        <view class="block-info-item">
          <view class="label">
            售后原因
          </view>
          <view class="content">
            {{ aftersales?.reason }}
          </view>
        </view>
        <view class="block-info-item">
          <view class="label">
            退款金额
          </view>
          <view class="content">
            {{
              aftersales?.refund_amount
                ? `¥${aftersales.refund_amount.toFixed(2)}`
                : '-'
            }}
          </view>
        </view>
        <view class="block-info-item">
          <view class="label">
            售后件数
          </view>
          <view class="content">
            {{ aftersales?.num ?? '-' }}
          </view>
        </view>
        <view class="block-info-item">
          <view class="label">
            联系方式
          </view>
          <view class="content">
            {{ aftersales?.mobile ?? '-' }}
          </view>
        </view>
        <view class="block-info-item">
          <view class="label">
            申请描述
          </view>
          <view class="content">
            {{ aftersales?.customer_remark ?? '-' }}
          </view>
        </view>
        <view class="block-info-item">
          <view class="label">
            申请图片
          </view>
          <view class="image-list">
            <v-image
              v-for="(img, index) in aftersales?.image"
              :key="index"
              :src="img"
              height="150rpx"
              width="150rpx"
              border-radius="8rpx"
              mode="aspectFill"
              preview
            />
          </view>
        </view>
      </view>
      <view class="aftersales-block" @click="navigateToLogs">
        <view class="block-info-header">
          <view class="block-info-title">
            协商历史
          </view>
          <view class="content">
            <wd-icon name="arrow-right" size="24rpx" color="#999999" />
          </view>
        </view>
      </view>
    </template>
    <template #footer>
      <view class="footer">
        <v-button
          v-if="ableToCancel"
          :custom-style="{
            height: '78rpx',
            padding: '0 28rpx',
            minWidth: '168rpx'
          }"
          @click="cancelApply"
        >
          撤销申请
        </v-button>
        <v-button
          v-if="ableToModify"
          :custom-style="{
            height: '78rpx',
            padding: '0 28rpx',
            minWidth: '168rpx'
          }"
          type="primary"
          @click="navigateToModify"
        >
          修改申请
        </v-button>
      </view>
    </template>
  </v-page>
</template>

<script setup lang="ts">
import { formateDateTime } from '@/utils/formater';

const aftersalesId = ref('');
const aftersales = ref<BackRefundVO>();
const address = computed(() => {
  const info = aftersales.value?.merchant_recipient_info;
  if (!info) return '';
  return `${info.prov}${info.city}${info.area}${info.address}`;
});
const buyerShippingText = computed(() => {
  const info = aftersales.value?.merchant_recipient_info;
  if (!info) return '';
  if (!info.delivery_name || !info.delivery_no) return '';
  return `${info.delivery_name} ${info.delivery_no}`;
});
const getAftersales = async () => {
  const response = await $api.getBackRefundDetailId(aftersalesId.value);
  switch (response.__error) {
    case undefined:
      aftersales.value = response.data;
      break;
    default:
      aftersales.value = undefined;
  }
};
const aftersalesProgress = ref<BackRefundProgressVO>();
const getAftersalesProgress = async () => {
  const response = await $api.getBackRefundProgressId(aftersalesId.value);
  switch (response.__error) {
    case undefined:
      aftersalesProgress.value = response.data;
      break;
    default:
      aftersalesProgress.value = undefined;
  }
};
const loading = ref(true);
onLoad((query) => {
  aftersalesId.value = query?.id as string;
});
const refreshPage = async () => {
  // loading.value = true;
  await Promise.all([getAftersales(), getAftersalesProgress()]);
  loading.value = false;
  if (!aftersales.value || !aftersalesProgress.value) uni.navigateBack();
};
onShow(refreshPage);

const refreshing = ref(false);
const refreshHandle = async () => {
  refreshing.value = true;
  await Promise.all([getAftersales(), getAftersalesProgress()]);
  refreshing.value = false;
};

const progressCurrent = computed(() => {
  if (!aftersalesProgress.value) return;
  const status = aftersalesProgress.value.mini_status;
  const startTime = aftersalesProgress.value.start_time;
  const overtime = aftersalesProgress.value.overtime;
  const amount = aftersalesProgress.value.amount;
  const content = aftersalesProgress.value.content;
  const overTimeDate = new Date(overtime);
  let overTimeRest = overTimeDate.getTime() - Date.now();
  if (overTimeRest < 0) overTimeRest = NaN;
  switch (status) {
    case 'MERCHANT_EXAMINE_REFUND':
      return {
        main: '待商家同意退款',
        sub: '',
        content: [
          { text: '若商家在', highlight: false },
          isNaN(overTimeRest)
            ? { text: overtime, highlight: true }
            : { time: overTimeRest },
          { text: '内未处理，将自动同意退款', highlight: false }
        ]
      };
    case 'REFUND_SUCCESS':
      return {
        main: '商家已同意退款，售后成功',
        content: [
          { text: '已于', highlight: false },
          { text: startTime, highlight: true },
          { text: '成功退款', highlight: false },
          { text: amount ? `¥${amount.toFixed(2)}` : '0.00', highlight: true },
          {
            text: `，并退回${$api._config.platform}原支付账号`,
            highlight: false
          }
        ]
      };
    case 'MERCHANT_APPROVAL_REFUND':
      return {
        main: '商家已同意退款',
        sub: '',
        content: [
          { text: '商家已于', highlight: false },
          { text: startTime, highlight: true },
          {
            text: `同意退款，预计24小时内退回${$api._config.platform}原支付账号`,
            highlight: false
          }
        ]
      };
    case 'MERCHANT_REFUSED_REFUND':
      return {
        main: '商家已拒绝退款',
        sub: `拒绝说明：${content} `,
        content: [
          { text: '拒绝说明：', highlight: false },
          { text: content, highlight: true },
          { text: '您可在', highlight: false },
          isNaN(overTimeRest)
            ? { text: overtime, highlight: true }
            : { time: overTimeRest },
          {
            text: '处理，超时则售后单将自动关闭。可联系商家协商，或重新修改申请',
            highlight: false
          }
        ]
      };
    case 'MERCHANT_OVERTIME_AUTO':
      return {
        main: '商家超时未处理，已自动退款',
        sub: '',
        content: [
          { text: '商家已于', highlight: false },
          { text: startTime, highlight: true },
          {
            text: `自动同意退款，预计24小时内退回${$api._config.platform}原支付账号`,
            highlight: false
          }
        ]
      };
    case 'REFUND_BUYER_CANCEL_APPLY':
      return {
        main: '您已撤销申请，已自动关闭售后单',
        sub: '',
        content: [
          { text: '已于', highlight: false },
          { text: startTime, highlight: true },
          { text: '关闭售后单', highlight: false }
        ]
      };
    case 'REFUND_BUYER_OVERTIME_AUTO':
      return {
        main: '您超时未处理，已自动关闭售后单',
        sub: '',
        content: [
          { text: '已于', highlight: false },
          { text: startTime, highlight: true },
          { text: '自动关闭售后单', highlight: false }
        ]
      };
    case 'MERCHANT_EXAMINE_SALE_RETURN':
      return {
        main: '待商家处理退货退款',
        sub: '',
        content: [
          { text: '若商家在', highlight: false },
          isNaN(overTimeRest)
            ? { text: overtime, highlight: true }
            : { time: overTimeRest },
          { text: '内未处理，将无退货/自动退款', highlight: false }
        ]
      };
    case 'MERCHANT_BUYER_UNSHIPPED':
      return {
        main: '商家已同意退货退款，待寄回',
        sub: '',
        content: [
          { text: '您可在', highlight: false },
          isNaN(overTimeRest)
            ? { text: overtime, highlight: true }
            : { time: overTimeRest },
          {
            text: '处理，超时则售后单将自动关闭。可联系商家协商，或重新修改申请',
            highlight: false
          }
        ]
      };
    case 'MERCHANT_BUYER_REFUSED':
      return {
        main: '商家拒绝退货退款，请您处理',
        sub: `拒绝说明：${content} `,
        content: [
          { text: '您可在', highlight: false },
          isNaN(overTimeRest)
            ? { text: overtime, highlight: true }
            : { time: overTimeRest },
          {
            text: '处理，超时则售后单将自动关闭。可联系商家协商，或重新申请',
            highlight: false
          }
        ]
      };
    case 'BUYER_SHIPPED_C':
      return {
        main: '已寄出，待商家确认收货并退款',
        content: [
          { text: '若商家在', highlight: false },
          isNaN(overTimeRest)
            ? { text: overtime, highlight: true }
            : { time: overTimeRest },
          { text: '内未处理，超时则系统自动为买家退款', highlight: false }
        ]
      };
    case 'MERCHANT_REFUSED_C':
      return {
        main: '商家拒绝收货并退款，请您处理',
        sub: `拒绝说明：${content} `,
        content: [
          { text: '您可在', highlight: false },
          isNaN(overTimeRest)
            ? { text: overtime, highlight: true }
            : { time: overTimeRest },
          {
            text: '处理，超时则售后单将自动关闭。可联系商家协商，或重新申请',
            highlight: false
          }
        ]
      };
    case 'SALE_RETURN_SUCCESS':
      return {
        main: '退款成功',
        sub: '',
        content: [
          { text: '已于', highlight: false },
          { text: startTime, highlight: true },
          { text: '成功退款', highlight: false },
          { text: amount ? `¥${amount.toFixed(2)}` : '0.00', highlight: true },
          {
            text: `，并退回${$api._config.platform}原支付账号`,
            highlight: false
          }
        ]
      };
    case 'SALE_RETURN_MERCHANT_OVERTIME_AUTO':
      return {
        main: '商家超时未处理，已自动退款',
        sub: '',
        content: [
          { text: '商家已于', highlight: false },
          { text: startTime, highlight: true },
          {
            text: `自动同意退款，预计24小时内退回${$api._config.platform}原支付账号`,
            highlight: false
          }
        ]
      };
    case 'BUYER_CANCEL_APPLY':
      return {
        main: '您已撤销申请，已自动关闭售后单',
        sub: '',
        content: [
          { text: '已于', highlight: false },
          { text: startTime, highlight: true },
          { text: '关闭售后单', highlight: false }
        ]
      };
    case 'MERCHANT_OVERTIME_RECEIVED_C':
      return {
        main: '商家超时未确认收货，已自动退款',
        sub: '',
        content: [
          { text: '商家已于', highlight: false },
          { text: startTime, highlight: true },
          {
            text: `自动同意退款，预计24小时内退回${$api._config.platform}原支付账号`,
            highlight: false
          }
        ]
      };
    case 'MERCHANT_RECEIVED_C':
      return {
        main: '商家已确认收货并退款',
        sub: '',
        content: [
          { text: '商家已于', highlight: false },
          { text: startTime, highlight: true },
          {
            text: `同意退款，预计24小时内退回${$api._config.platform}原支付账号`,
            highlight: false
          }
        ]
      };
    default:
      return undefined;
  }
});
const stepsList = computed(() => {
  if (!aftersalesProgress.value) return;
  const list = aftersalesProgress.value.node_list;
  const steps: { title: string; sub: string }[] = [];
  const apply = list.find((item) => item.node === 'APPLY');
  if (apply) {
    steps.push({
      title: '提交申请',
      sub: formateDateTime(apply.time, 'M-DD hh:mm') || '-'
    });
  }
  const examine = list.find((item) => item.node === 'EXAMINE');
  if (examine) {
    steps.push({
      title: '商家处理',
      sub: formateDateTime(examine.time, 'M-DD hh:mm') || '-'
    });
  }
  const shipped = list.find((item) => item.node === 'SHIPPED');
  if (shipped) {
    steps.push({
      title: '寄回商品',
      sub: formateDateTime(shipped.time, 'M-DD hh:mm') || '-'
    });
  }
  const refund = list.find((item) => item.node === 'REFUND');
  if (refund) {
    steps.push({
      title: '商家退款',
      sub: formateDateTime(refund.time, 'M-DD hh:mm') || '-'
    });
  }
  const success = list.find((item) => item.node === 'SUCCESS');
  if (success) {
    steps.push({
      title: '售后完成',
      sub: formateDateTime(success.time, 'M-DD hh:mm') || '-'
    });
  }
  return steps;
});
const stepsCurrent = computed(() => {
  if (!aftersalesProgress.value) return;
  const list = aftersalesProgress.value.node_list;
  for (let i = list.length - 1; i >= 0; i -= 1) {
    if (list[i].status === 'PROCESSING') return i;
    if (list[i].status === 'PROCESSED') return i;
  }
  return 0;
});

const aftersalesType = computed(() => {
  if (!aftersales.value) return '';
  switch (aftersales.value.type) {
    case 'BARTER':
      return '退货换货';
    case 'REFUND':
      return '仅退款';
    case 'SALE_RETURN':
      return '退货退款';
    default:
      return '';
  }
});

const ableToCancel = computed(() => {
  if (!aftersalesProgress.value) return false;
  switch (aftersalesProgress.value.mini_status) {
    case 'MERCHANT_EXAMINE_REFUND':
    case 'MERCHANT_EXAMINE_SALE_RETURN':
    case 'MERCHANT_APPROVAL_REFUND':
    case 'MERCHANT_BUYER_UNSHIPPED':
    case 'MERCHANT_REFUSED_REFUND':
    case 'MERCHANT_BUYER_REFUSED':
    case 'BUYER_SHIPPED_C':
    case 'MERCHANT_REFUSED_C':
      return true;
    default:
      return false;
  }
});

const ableToModify = computed(() => {
  if (!aftersalesProgress.value) return false;
  switch (aftersalesProgress.value.mini_status) {
    case 'MERCHANT_REFUSED_REFUND':
    case 'MERCHANT_BUYER_REFUSED':
    case 'MERCHANT_REFUSED_C':
      return true;
    default:
      return false;
  }
});

const copyHandle = () => {
  if (!aftersales.value?.merchant_recipient_info) return;
  const list: string[] = [];
  list.push(`收货人: ${aftersales.value.merchant_recipient_info.recipient}`);
  list.push(
    `联系电话: ${aftersales.value.merchant_recipient_info.recipient_mobile}`
  );
  list.push(`收货地址: ${aftersales.value.merchant_recipient_info.address}`);
  uni.setClipboardData({
    data: list.join('\n'),
    success: () => {
      uni.showToast({ title: '复制成功', icon: 'none' });
    }
  });
};

const cancelApply = async () => {
  const result = await uni.showModal({
    title: '提示',
    content: '是否确定撤销申请？撤销后，将关闭当前售后单'
  });
  if (!result.confirm) return;
  uni.showLoading({ mask: true });
  const response = await $api.putBackRefundModifyIdCancel(aftersalesId.value);
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '撤销成功', icon: 'none' });
      uni.$emit('refresh-order-list');
      refreshPage();
      break;
  }
};
const navigateToModify = () => {
  if (!aftersales.value) return;
  const pageStore = $store.page();
  pageStore.setParameters({
    id: aftersales.value.order_id,
    aftersalesId: aftersalesId.value,
    type: aftersales.value.type,
    reason: aftersales.value.reason,
    product: aftersales.value.back_refund_details[0],
    customer_remark: aftersales.value.customer_remark,
    image: aftersales.value.image,
    mobile: aftersales.value.mobile,
    amount: aftersales.value.apply_amount,
    quantity: aftersales.value.num
  });
  uni.navigateTo({
    url: '/pages/aftersales/aftersales-apply?modify=true'
  });
};
const navigateToExpress = () => {
  uni.navigateTo({
    url: `/pages/aftersales/aftersales-express?id=${aftersalesId.value}`
  });
};
const navigateToLogs = () => {
  uni.navigateTo({
    url: `/pages/aftersales/aftersales-logs?id=${aftersalesId.value}`
  });
};
</script>

<style lang="scss" scoped>
.aftersales-block {
  margin: 0 24rpx 24rpx;
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 12rpx;

  .block-info-title {
    font-weight: bold;
    flex-shrink: 0;
  }

  .block-info-sub {
    font-size: 24rpx;
  }

  .block-info-content {
    color: #999999;
    .highlight {
      color: #ff2f3b;
      margin: 0 4rpx;
    }
    :deep(.wd-count-down) {
      display: inline;
      color: #ff2f3b;
      margin: 0 4rpx;
      font-size: inherit;
    }
  }

  .block-info-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16rpx;
    min-height: 60rpx;
    .copy-button {
      padding: 4rpx 8rpx;
      color: #ff2f3b;
    }
    .express {
      display: flex;
      align-items: center;
      gap: 16rpx;
      .text {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .placeholder {
        color: #999999;
      }
      .icon {
        flex-shrink: 0;
      }
    }
  }

  .divider {
    height: 1px;
    background-color: #eeeeee;
  }

  .block-info-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 24rpx;
    min-height: 60rpx;
    .label {
      flex-shrink: 0;
    }
    .sub-label {
      color: #999999;
      font-weight: 300;
      flex: 1;
      min-width: 0;
    }
    .content {
      flex: 1;
      min-width: 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 12rpx;
      &.placeholder {
        color: #999999;
        font-weight: 300;
      }
    }
    .image-list {
      flex: 1;
      min-width: none;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      flex-wrap: wrap;
      gap: 12rpx;
    }
  }
}
.footer {
  display: flex;
  justify-content: flex-end;
  gap: 30rpx;
  padding: 12rpx 24rpx 0;
}
</style>
